﻿using System;
using System.Data.Objects;
using System.Linq;
using NOSDC.Entities;
using NOSDC.Pocos;

namespace NOSDC.Repositories.Users
{
    public sealed class AccountRepository : IAccountRepository
    {
        private readonly NOSDCContext _context = new NOSDCContext();

        public void AddPasswordRecoveryRequest(PasswordRecovery passwordRecoveryRequest)
        {
            _context.PasswordRecoveryRequest.AddObject(passwordRecoveryRequest);
            _context.SaveChanges();
        }

        public PasswordRecovery HasValidPasswordRecoveryRequest(Guid recoveryId)
        {
            return _context.PasswordRecoveryRequest.FirstOrDefault(p => p.RecoveryToken == recoveryId);
        }

        public void HasRecoveredPassword(Guid recoveryId, DateTime date)
        {
            var request = _context.PasswordRecoveryRequest.First(p => p.RecoveryToken == recoveryId);

            request.DateRecovered = date;
            request.HasRecovered = true;

            _context.PasswordRecoveryRequest.Attach(request);
            var requestEntry = _context.ObjectStateManager.GetObjectStateEntry(request);

            requestEntry.SetModified();
            _context.ObjectStateManager.ChangeObjectState(request, System.Data.EntityState.Modified);

            _context.SaveChanges(SaveOptions.DetectChangesBeforeSave);
        }
    }
}
